package com.huahai.security.core.authentication.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Jun
 * @Date: 2020/7/19
 *
 * 解决未登录用户访问无权限资源时的异常
 *
 * AuthenticationEntryPoint 的默认实现类是 LoginUrlAuthenticationEntryPoint，
 * 因此默认的认证异常处理逻辑就是 LoginUrlAuthenticationEntryPoint#commence 方法
 * 简单说就是重定向，重定向到登录页面（即当我们未登录就去访问一个需要登录才能访问的资源时，会自动重定向到登录页面）
 */
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        PrintWriter printWriter = response.getWriter();
        Map<String, String> map = new HashMap<>(2);
        map.put("status", "401");
        map.put("message", "请登录后再进行访问!");
        String resBody = objectMapper.writeValueAsString(map);
        printWriter.print(resBody);
        printWriter.flush();
        printWriter.close();
    }

}
